from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from app import models
from django.core.paginator import Paginator
from django.core import serializers
import hashlib
import re

# Create your views here.
userName=None

def password_reset(request):
    '''
    重置用户密码
    :param request:
    :return:
    '''
    if request.method == 'GET':
        return render(request,'password_reset.html')
    else:
        username = request.POST.get('username')
        phone = request.POST.get('phone')
        new_password = request.POST.get('new_password')
        new_password_md5 = hashlib.md5(new_password.encode(encoding='utf-8')).hexdigest()
        try:
            user = models.RegistUser.objects.get(username=username)
            if phone == user.phone:
                if new_password_md5 == user.password:
                    return render(request, 'password_reset.html', {'msg': '新密码不能和旧密码相同'})
                elif len(new_password)<6:
                    return render(request, 'password_reset.html', {'msg': '新密码过短，请重新输入新密码'})
                else:
                    user.password = new_password_md5
                    user.save()
                return render(request,'password_reset.html',{'msg':'密码重置成功'})
            else:
                return render(request, 'password_reset.html', {'msg': '预留手机号错误，请重新输入'})
        except:
            return render(request,'password_reset.html',{'msg':'用户名不存在，请重新输入'})

def login(request):
    if request.method == 'GET':
        return render(request, '../static/../templates/login.html')
    else:
        username = request.POST.get('name')
        password = request.POST.get('password')
        #条件查询
        global userName
        userName=None
        try:
            user = models.RegistUser.objects.get(username=username)
        except:
            return render(request, '../static/../templates/login.html', {'msg': '登录失败，用户名不存在！'})
        if user.password == hashlib.md5(password.encode(encoding='utf-8')).hexdigest():   #加密比较
            userName=username
            return redirect('/main/')
        else:
            return render(request, '../static/../templates/login.html', {'msg': '登录失败，密码错误！'})

def regist(request):
    if request.method == 'GET':
        return render(request,'regist.html')
    else:
        username = request.POST.get('name')
        password = request.POST.get('password')
        repeatpwd = request.POST.get('repeatpwd')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        try:
            user_data = models.RegistUser.objects.get(username=username)
            return render(request,'regist.html',{'msg':'此用户名已被使用，请使用其他用户名'})
        except:
            if password != repeatpwd:
                return render(request, 'regist.html', {'msg': '注册失败，两次密码不一致','username':username})
            elif len(password)<6:
                return render(request, 'regist.html', {'msg': '注册失败，不符合格式', 'username': username})
            elif len(phone)<11:
                return render(request, 'regist.html', {'msg': '注册失败，手机号不符合格式','username':username})
            else:
                password=hashlib.md5(password.encode(encoding='utf-8')).hexdigest()  #加密
                user = models.RegistUser(username=username, password=password, email=email, phone=phone)
                user.save()
                return redirect('/login/')

def mainView(request):
        if userName==None:
            return redirect('/login/')
        else:
            return render(request, 'main.html',{'msg':'欢迎登录，'+userName})

def logout(request):
    global userName
    userName=None
    print(userName)
    return redirect('/login/')

def loadAllData(request):
    all_data = models.WeatherData.objects.all().values()
    page_count = len(all_data)

    # 前台传来的页数
    page_index = request.GET.get('page')
    # 前台传来的一页显示多少条数据
    page_limit = request.GET.get('limit')
    # 分页器进行分配
    paginator = Paginator(all_data, page_limit)
    # 前端传来页数的数据
    data = paginator.page(page_index)
    # 放在一个列表里
    all_data_info = [x for x in data]
    datas = {"code": 0, "msg": "", "count": page_count, "data": all_data_info}
    return JsonResponse(datas)

def search(request):
    if request.method == 'GET':
        if userName==None:
            return redirect('/login/')
        else:
            return render(request, 'search.html',{'msg':'欢迎登录，'+userName})

# xxxxxxxxxxxxxxxxx
def loadSearchStateData(request):
    state_value = request.GET.get('query')
    state_items = models.WeatherData.objects.filter(state=state_value).values()
    page_count = len(state_items)
    # 前台传来的页数
    page_index = request.GET.get('page')
    # 前台传来的一页显示多少条数据
    page_limit = request.GET.get('limit')
    # 分页器进行分配
    paginator = Paginator(state_items, page_limit)
    # 前端传来页数的数据
    data = paginator.page(page_index)
    # 放在一个列表里
    all_data_info = [x for x in data]
    datas = {"code": 0, "msg": "", "count": page_count, "data": all_data_info}
    return JsonResponse(datas)

def loadSearchCityData(request):
    city_value = request.GET.get('query')
    city_items = models.WeatherData.objects.filter(city=city_value).values()
    page_count = len(city_items)
    # 前台传来的页数
    page_index = request.GET.get('page')
    # 前台传来的一页显示多少条数据
    page_limit = request.GET.get('limit')
    # 分页器进行分配
    paginator = Paginator(city_items, page_limit)
    # 前端传来页数的数据
    data = paginator.page(page_index)
    # 放在一个列表里
    all_data_info = [x for x in data]
    datas = {"code": 0, "msg": "", "count": page_count, "data": all_data_info}
    return JsonResponse(datas)

def loadSearchDtData(request):
    dt_value = request.GET.get('query')
    dt_items = models.WeatherData.objects.filter(dt=dt_value).values()
    page_count = len(dt_items)
    # 前台传来的页数
    page_index = request.GET.get('page')
    # 前台传来的一页显示多少条数据
    page_limit = request.GET.get('limit')
    # 分页器进行分配
    paginator = Paginator(dt_items, page_limit)
    # 前端传来页数的数据
    data = paginator.page(page_index)
    # 放在一个列表里
    all_data_info = [x for x in data]
    datas = {"code": 0, "msg": "", "count": page_count, "data": all_data_info}
    return JsonResponse(datas)

def loadSelectData(request):
    state_datas = models.WeatherData.objects.all().values('state').distinct()
    city_datas = models.WeatherData.objects.all().values('city').distinct()
    dt_datas = models.WeatherData.objects.all().values('dt').distinct()

    # 注意：QuerySet类型无法直接序列化，需要将其转成列表
    dic = {
        'state_datas': list(state_datas),
        'city_datas': list(city_datas),
        'dt_datas': list(dt_datas),
    }
    return JsonResponse(dic)


from django.db.models import Avg, Sum, Max, Min, Count


def max_temp_state(request):
    if userName == None:
        return redirect('/login/')
    else:
        name = []
        data = []
        state_max_temps = models.WeatherData.objects.values('state').annotate(Max('max_temp'))
        for dic in state_max_temps:
            name.append(dic['state'])
            data.append(dic['max_temp__max'])
        return render(request, "max_temp_state.html", {"name": name, "data": data,'msg':'欢迎登录，'+userName})


def min_temp_state(request):
    if userName == None:
        return redirect('/login/')
    else:
        name = []
        data = []
        state_max_temps = models.WeatherData.objects.values('state').annotate(Min('min_temp'))
        for dic in state_max_temps:
            name.append(dic['state'])
            data.append(dic['min_temp__min'])
        return render(request, "min_temp_state.html", {"name": name, "data": data,'msg':'欢迎登录，'+userName})


def chinaMap(request):
    city_max_temps = models.WeatherData.objects.values('city').annotate(Max('max_temp'))
    city_max_temps = list(city_max_temps)
    # 地图的数据必须要求字典的key为name和value
    # 将原始orm请求到的数据中字典的key进行更换（原始字典：{'city': '北京', 'max_temp__max': '33'}）
    province_capital_dict = {
        '山东': '济南',
        '河北': '石家庄',
        '吉林': '长春',
        '黑龙江': '哈尔滨',
        '辽宁': '沈阳',
        '内蒙古': '呼和浩特',
        '新疆': '乌鲁木齐',
        '甘肃': '兰州',
        '宁夏': '银川',
        '山西': '太原',
        '陕西': '西安',
        '河南': '郑州',
        '安徽': '合肥',
        '江苏': '南京',
        '浙江': '杭州',
        '福建': '福州',
        '广东': '广州',
        '江西': '南昌',
        '海南': '海口',
        '广西': '南宁',
        '贵州': '贵阳',
        '湖南': '长沙',
        '湖北': '武汉',
        '四川': '成都',
        '云南': '昆明',
        '西藏': '拉萨',
        '青海': '西宁',
        '天津': '天津',
        '上海': '上海',
        '重庆': '重庆',
        '北京': '北京',
        '台湾': '台北',
        '香港': '香港',
        '澳门': '澳门'
    }
    capital_province_dict = {v: k for k, v in province_capital_dict.items()}

    t_list_data_dict = {}
    for dic_item in city_max_temps:
        city = dic_item['city']
        if city in province_capital_dict.keys():
            t_list_data_dict[city] = {'name': city, 'value': dic_item['max_temp__max']}
        elif city in capital_province_dict.keys():
            if capital_province_dict[city] not in t_list_data_dict.keys():
                t_list_data_dict[capital_province_dict[city]] = {'name': capital_province_dict[city], 'value': dic_item['max_temp__max']}
    t_list_datas = [value for key, value in t_list_data_dict.items()]

    # t_list_datas = []
    # for dic_item in city_max_temps:
    #     city = dic_item['city']
    #     if city in province_capital_dict.keys():
    #         t_list_datas.append({'name': city, 'value': dic_item['max_temp__max']})
    #     elif city in capital_province_dict.keys():
    #         t_list_datas.append({'name': capital_province_dict[city], 'value': dic_item['max_temp__max']})
    if userName == None:
        return redirect('/login/')
    else:
        return render(request,'chinaMap.html',{'data':t_list_datas,'msg':'欢迎登录，'+userName})
